package cz.possoft.boot;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;

/**
 * This class can be used to obtain instances of classloader, which can load all jar files from specified directory.
 * 
 * Example of usage: 
 * 
 * 1)
 * classloader = BootClassLoaderUtils.getInstanceFordirectory("lib") - return classloader which is child of system classloader and in 
 * addition is able to load classes from all jars from specified directory. 
 * 
 * 2)
 * classloader = BootClassLoaderUtils.getInstanceForDirectory("lib", parentClassloader) - return classloader which is child of parentClassloader and in 
 * addition is able to load classes from all jars from specified directory. 
 * 
 * @author mposolda
 */
public class BootClassLoaderUtils {
	
	private BootClassLoaderUtils()
	{
	}
	
	public static URLClassLoader getInstanceForDirectory(String directory)
	{
		List<URL> JARFilesURLs = returnJarFilesAsURLs(directory);
		return new URLClassLoader(JARFilesURLs.toArray(new URL[] {}), ClassLoader.getSystemClassLoader());
	}
	
	public static URLClassLoader getInstanceForDirectory(String directory, ClassLoader parent)
	{
		List<URL> JARFilesURLs = returnJarFilesAsURLs(directory);
		return new URLClassLoader(JARFilesURLs.toArray(new URL[] {}), parent);
	}	
	
	/**
	 * Return jar files from base directory.
	 * 
	 * @param directory
	 * @return
	 */
	private static List<URL> returnJarFilesAsURLs(String directory)
	{
			try {
				File libDirectory = new File(directory);
				if ((!libDirectory.exists()) || (!libDirectory.isDirectory()))
				{
					throw new IllegalArgumentException(directory  + " does not exists or is not a directory.");
				}
			
				// list files from given directory.
				File[] files = libDirectory.listFiles();
			
				// filter files and count only jar files.
				List<URL> jarsToOutput = new ArrayList<URL>(8);
				for (File file : files) 
				{
					if (file.getName().endsWith(".jar")) 
					{
						jarsToOutput.add(file.toURI().toURL());
					}
				}
				return jarsToOutput;
			}
			catch (MalformedURLException mue)
			{
				throw new IllegalArgumentException("Bad URL when trying to load JARs from directory " + directory);
			}
	}	

}
